package com.bjsc.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bjsc.entity.SpendRecord;
import com.bjsc.enums.SpendTypeEnum;
import com.bjsc.mapper.UserMapper;
import com.bjsc.service.IRechargeService;
import com.bjsc.mapper.SpendRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author create by VIC.Huang
 * @date 2018/2/8
 */
@Service
public class RechargeServiceImpl extends ServiceImpl<SpendRecordMapper, SpendRecord> implements IRechargeService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<Map<Object, Object>> selectRechargePage(Page<Map<Object, Object>> page) {
        page.setRecords(baseMapper.selectSpendRecordList(page, SpendTypeEnum.RECHARGE.getCode()));
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recharge(Long userId, BigDecimal money) {
        // 查看用户是否存在且未冻结
        if(userMapper.countUserById(userId) == 0) {
            throw new RuntimeException("用户不存在！");
        }
        if(userMapper.updateUserAsset(userId, money) > 0) {
            userMapper.insertSpendRecord(userId, SpendTypeEnum.RECHARGE.getCode(), money);
            return true;
        }else {
            return false;
        }
    }
}
